package com.ggs.rg.ybjb.adminmodule.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ggs.rg.ybjb.adminmodule.exception.GoodsException;
import com.ggs.rg.ybjb.adminmodule.service.GoodsService;
import com.ggs.rg.ybjb.adminmodule.service.MaterService;
import com.ggs.rg.ybjb.adminmodule.service.TCommentService;
import com.ggs.rg.ybjb.adminmodule.service.UserService;
import com.ggs.rg.ybjb.adminmodule.util.ImageUtil;
import com.ggs.rg.ybjb.adminmodule.util.ListPagesUitl;
import com.ggs.rg.ybjb.adminmodule.util.OrderUtil;
import com.ggs.rg.ybjb.pojomodule.pojo.*;
import com.ggs.rg.ybjb.pojomodule.util.CommonUtil;
import com.ggs.rg.ybjb.pojomodule.util.StringTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ClassName:GoodsController
 * Package:com.ggs.rg.ybjb.adminmodule.controller
 * Description:
 *
 * @Date:2021/11/4 10:41
 * @Author:cxw
 */
@RestController
@RequestMapping("/goodsModule")
public class GoodsController {

    @Autowired
    GoodsService goodsService;

    @Autowired
    MaterService materService;

    @Autowired
    TCommentService tCommentService;

    @Autowired
    UserService userService;

    //添加商品
    //商品表内没有，添加商品表，再根据gid添加参数表
    @PostMapping(value="/addGoods")
    @Transactional(rollbackFor = GoodsException.class)
    public JSONObject addGoods(@RequestParam("name") String name,
                               @RequestParam("gDesc") String gDesc,
                               @RequestParam("status") Integer status,
                               @RequestParam("type") String type,
                               @RequestParam("p1") MultipartFile p1,
                               @RequestParam("goodsList") String goodsList) throws GoodsException, IOException {
        JSONObject result = new JSONObject();
        //保存图片
        String newName = ImageUtil.getNewFileName(p1);
        Goods goods = new Goods(name,gDesc,newName,status,type);
        boolean addGoodsResult = goodsService.save(goods);
        if (!addGoodsResult){
            throw new GoodsException();
        }
        //插入数据，并返回自增的ID
        ImageUtil.saveFile(newName,p1);
        int gid = goods.getGid();
        JSONArray maters = JSON.parseArray(goodsList);
        for(int i=0;i<maters.size();i++){
            JSONObject mater = maters.getJSONObject(i);
            String text = mater.getString("text");
            Double price = mater.getDouble("price");
            int count = mater.getInteger("count");
            Mater m = new Mater(text,price,count,gid);
            boolean addMaterResult = materService.save(m);
            if (!addMaterResult)
                throw new GoodsException();
        }
        result.put("result",true);
        return result;
    }

    /*
    删除商品，连带着商品参数一起删除
    */
    @PostMapping("/deleteGoods")
    public JSONObject deleteAllGoods(@RequestParam("gid")Integer gid){
        JSONObject result = new JSONObject();
////        Integer gid = jsonObject.getInteger("gid");
        List<Integer> gidList = new ArrayList<>();
        if (!StringTools.isNullOrEmpty(gid)){
            QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
            QueryWrapper<Goods> select = queryWrapper.select("gid");
            List<Goods> list = goodsService.list(select);
            for (Goods g : list){
                gidList.add(g.getGid());
            }
            if (gidList.contains(gid)){
                //删除商品
                goodsService.removeById(gid);
                //同时关联的参数表也被逻辑删除
                QueryWrapper<Mater> queryWrapper1 = new QueryWrapper<>();
                QueryWrapper<Mater> select1 = queryWrapper1.eq("gid", gid).select("pid");
                List<Mater> list1 = materService.list(select1);
                for (Mater m : list1){
                    int pid = m.getPid();
                    materService.removeById(pid);
                }
                //同时关联的评论表也被逻辑删除
                QueryWrapper<TComment> queryWrapper2 = new QueryWrapper<>();
                QueryWrapper<TComment> select2 = queryWrapper2.eq("gid", gid).select("cid");
                List<TComment> list2 = tCommentService.list(select2);
                for (TComment tc : list2){
                    Integer cid = tc.getCid();
                    tCommentService.removeById(cid);
                }
                result.put("result",true);
            }else {
                result.put("result",false);
            }
        }else {
            result.put("result",false);
        }
        return result;
    }

    /*
    删除商品某一个参数值
     */
    @PostMapping("/deleteMater")
    public JSONObject deleteGoodsMater(@RequestParam("pid")Integer pid){
        JSONObject result = new JSONObject();
        List<Integer> pidList = new ArrayList<>();
        if (!StringTools.isNullOrEmpty(pid)){
            QueryWrapper<Mater> queryWrapper = new QueryWrapper<>();
            QueryWrapper<Mater> select = queryWrapper.select("pid");
            List<Mater> list = materService.list(select);
            for (Mater m : list){
                pidList.add(m.getPid());
            }
            if (pidList.contains(pid)){
                materService.removeById(pid);
                result.put("result",true);
            }else {
                result.put("result",false);
            }
        }else {
            result.put("result",false);
        }
        return result;
    }

    //查询商品 or 参数表关联的商品内容
    @GetMapping("/selectGoodsMater")
    public JSONObject selectGoodsAndMater(@RequestParam("gid") Integer gid){
        JSONObject result = new JSONObject();
        List<TComment> tCommentList = new ArrayList<>();
        if (!StringTools.isNullOrEmpty(gid)){
            QueryWrapper<Mater> queryWrapper = new QueryWrapper<>();
            //查询商品表内荣
            Goods goods = goodsService.getById(gid);
            String image1 = goods.getImage();
            String imageAddr1 = ImageUtil.getImageAddr(image1, "9001");
            goods.setImage(imageAddr1);
            //查询参数表内容
            QueryWrapper<Mater> select = queryWrapper.eq("gid",gid).select("pid","text","price","count","gid");
            List<Mater> list = materService.list(select);
            for (Mater m : list){
                int pid = m.getPid();
                //查询评论表
                QueryWrapper<TComment> queryWrapper1 = new QueryWrapper<>();
                QueryWrapper<TComment> select1 = queryWrapper1.eq("pid", pid).select("cid", "text", "image", "phone", "pid","oid", "text_manage");
                List<TComment> tComments = tCommentService.list(select1);
                //返回评论了用户的头像和名字
                for(TComment tc : tComments){
                    //评论图片
                    String image2 = tc.getImage();
                    if (StringTools.isNullOrEmpty(image2)){
                        tc.setImage(null);
                        String phone = tc.getPhone();
                        QueryWrapper<TUser> queryWrapper2 = new QueryWrapper<>();
                        QueryWrapper<TUser> select2 = queryWrapper2.eq("phone",phone).select("name","image");
                        TUser user = userService.getOne(select2);
                        String image = user.getImage();
                        String imageAddr = ImageUtil.getImageAddr(image, "9002");
                        user.setImage(imageAddr);
                        tc.setTUsers(user);
                        tCommentList.add(tc);
                    }else {
                        String imageAddr2 = ImageUtil.getImageAddr(image2, "9002");
                        tc.setImage(imageAddr2);
                        String phone = tc.getPhone();
                        QueryWrapper<TUser> queryWrapper2 = new QueryWrapper<>();
                        QueryWrapper<TUser> select2 = queryWrapper2.eq("phone",phone).select("name","image");
                        TUser user = userService.getOne(select2);
                        String image = user.getImage();
                        String imageAddr = ImageUtil.getImageAddr(image, "9002");
                        user.setImage(imageAddr);
                        tc.setTUsers(user);
                        tCommentList.add(tc);
                    }
                }
            }
            result.put("goods",goods);
            result.put("tComments",tCommentList);
            result.put("list",list);
        }
        else {
            result.put("Error","请输入正确的商品ID");
        }
        return result;
    }


    //模糊查询
    @PostMapping("/selectLike")
    public JSONObject selectLike(@RequestParam("name")String name,@RequestParam("pagesNumber")Integer pagesNumber){
        //判断分页
        if (StringTools.isNullOrEmpty(pagesNumber)){
            pagesNumber = 1;
        }else if (pagesNumber <= 0){
            pagesNumber = 1;
        }
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        QueryWrapper<Goods> like = queryWrapper.like("name", name).or().like("g_desc",name).select("gid","name","g_desc","image","status","type");
        //分页
        List<Goods> list = goodsService.list(like);
        for (Goods g : list){
            String image = g.getImage();
            String imageAddr = ImageUtil.getImageAddr(image, "9001");
            g.setImage(imageAddr);
        }
        Map<String, Object> map = ListPagesUitl.listPaging(list, pagesNumber, 10);
        return CommonUtil.successJson(map);
    }

    //获取所有商品，不包含参数  商品数量包含在里面
    @GetMapping("/selectGoods")
    public JSONObject selectGoods(@RequestParam(value = "pagesNumber",required = false) Integer pagesNumber){
        if (StringTools.isNullOrEmpty(pagesNumber)){
            pagesNumber = 1;
        }else if (pagesNumber <= 0){
            pagesNumber = 1;
        }
        //创建条件构造器
        QueryWrapper<Goods> wrapper = new QueryWrapper<Goods>();
        //向条件构造器加入条件
        QueryWrapper<Goods> select = wrapper.select("gid", "name", "g_desc", "image", "status", "type");
        //分页查询
        List<Goods> list = goodsService.list(select);
        for (Goods g : list){
            String image = g.getImage();
            String imageAddr = ImageUtil.getImageAddr(image, "9001");
            g.setImage(imageAddr);
        }
        Map<String, Object> map = ListPagesUitl.listPaging(list, pagesNumber, 10);
        return CommonUtil.successJson(map);
    }

    //添加库存
    @PostMapping("/addCount")
    public JSONObject addCount(@RequestParam("cid")Integer cid,@RequestParam("count")Integer count){
        JSONObject result = new JSONObject();
        if (!(StringTools.isNullOrEmpty(cid) || StringTools.isNullOrEmpty(count))){
            Mater mater1 = materService.getById(cid);
            int count1 = mater1.getCount();
            mater1.setCount(count + count1);
            materService.updateById(mater1);
            result.put("result",mater1);
        }else {
            result.put("result","请传入完整的参数！");
        }
        return result;
    }

    //查询缺货商品
    @GetMapping("/selectBackorder")
    public JSONObject selectCount(@RequestParam(value = "pagesNumber",required = false) Integer pagesNumber){
        if (StringTools.isNullOrEmpty(pagesNumber)){
            pagesNumber = 1;
        }else if (pagesNumber <= 0){
            pagesNumber = 1;
        }
        //创建分页对象
        List<Goods> list1 = new ArrayList<>();
        QueryWrapper<Mater> queryWrapper = new QueryWrapper<>();
        QueryWrapper<Mater> select = queryWrapper.le("count", 10).select("pid", "text", "price", "count", "gid");
        List<Mater> list = materService.list(select);
        for(Mater m : list){
            int gid = m.getGid();
            Goods goods = goodsService.getById(gid);
            String image = goods.getImage();
            String imageAddr = ImageUtil.getImageAddr(image, "9001");
            goods.setImage(imageAddr);
            goods.setMater(m);
            list1.add(goods);
        }
        //分页显示
//        List<Goods> list2 = ListPagesUitl.listPaging(list1, pagesNumber, 10);
        Map<String, Object> map = ListPagesUitl.listPaging(list1, pagesNumber, 10);
        //分页结果
        return CommonUtil.successJson(map);
    }

    //模糊查询缺货商品
    @PostMapping("/selectBackorderLike")
    public JSONObject selectCountLike(@RequestParam("name")String name,@RequestParam("pagesNumber")Integer pagesNumber){
        if (StringTools.isNullOrEmpty(pagesNumber)){
            pagesNumber = 1;
        }else if (pagesNumber <= 0){
            pagesNumber = 1;
        }
        if (!StringTools.isNullOrEmpty(name)){
            //创建分页对象
            List<Goods> list = new ArrayList<>();
            QueryWrapper<Mater> queryWrapper = new QueryWrapper<>();
            QueryWrapper<Mater> select = queryWrapper.le("count", 10).select("pid", "text", "price", "count", "gid");
            List<Mater> list1 = materService.list(select);
            for (Mater m : list1){
                int gid = m.getGid();
                Goods goods = goodsService.getById(gid);
                goods.setMater(m);
                String name1 = goods.getName();
                if (name1.contains(name)){
                    String image = goods.getImage();
                    String imageAddr = ImageUtil.getImageAddr(image, "9001");
                    goods.setImage(imageAddr);
                    list.add(goods);
                }
            }
            //分页显示
            Map<String, Object> map = ListPagesUitl.listPaging(list, pagesNumber, 10);
            return CommonUtil.successJson(map);
        }else {
            return CommonUtil.sqlErrorJson("请输入想要搜索的商品");
        }
    }
}
